﻿using System;
using System.Collections.Generic;
using System.Text;
using Roovent.HttpOperator;

namespace UnionnetClient.Model
{
	/* 登陆参数--用于外部设置 */
	public class AppSettings : SettingsHelper
	{
		static public readonly AppSettings Instance = new AppSettings();

		public AppSettings()
		{
			if (settings == null)
			{
				settings = new Dictionary<string, object>();

				#region 设置默认值
				this[SettingsProperty.AutoLogin] = true;
				this[SettingsProperty.IsVPN] = true;
				this[SettingsProperty.LoginAttemptInterval] = 5000;
				this[SettingsProperty.LoginTimeout] = 60000;
				this[SettingsProperty.Password] = String.Empty;
				this[SettingsProperty.Username] = String.Empty;
				#endregion
			}
		}

		public string Username
		{
			get { return (string)this[SettingsProperty.Username]; }
		}

		public string Password
		{
			get { return (string)this[SettingsProperty.Password]; }
		}

		public bool IsVPN
		{
			get { return (bool)this[SettingsProperty.IsVPN]; }
			set
			{
				if ((bool)this[SettingsProperty.IsVPN] != value)
				{
					this[SettingsProperty.IsVPN] = value;
					if (IsLoginSourceCorrect)
					{
						RefreshPostParameters();
					}
				}
			}
		}

		public int LoginAttemptInterval
		{
			get { return (int)this[SettingsProperty.LoginAttemptInterval]; }
			set { this[SettingsProperty.LoginAttemptInterval] = value; }
		}

		public int LoginTimeout
		{
			get { return (int)this[SettingsProperty.LoginTimeout]; }
			set { this[SettingsProperty.LoginTimeout] = value; }
		}

		public bool IsAccoutCorrect
		{
			get { return (string)this[SettingsProperty.Username] != String.Empty && (string)this[SettingsProperty.Password] != string.Empty; }
		}

		public bool IsLoginSourceCorrect
		{
			get { return this[SettingsProperty.LoginSource] != null; }
		}



		public void SetAccount(string username, string password)
		{
			AppEnvironment.CurrentState.SetAccount(username, password);
		}

		
		internal void SetAccoutInside(string username, string password)
		{
			if (username != string.Empty && password != string.Empty)
			{
				this[SettingsProperty.Username] = username;
				this[SettingsProperty.Password] = password;

				if (IsLoginSourceCorrect)
				{
					RefreshPostParameters();
				}
			}
			else
			{
				throw new ArgumentException("用户名和密码不能为空");
			}
		}

		internal void RefreshPostParameters()
		{
			HtmlForm form = FormParser.ParseForm((string)this[SettingsProperty.LoginSource]);
			form.Labels["uid"].Attributes["value"] = this.Username;
			form.Labels["upwd"].Attributes["value"] = this.Password;
			form.Labels["vpn"].Attributes["value"] = this.IsVPN ? "1" : "0";
			form.Labels["uact_status"].Attributes["value"] = "1";
			this[SettingsProperty.PostAddress] = form.Action;
			this[SettingsProperty.PostParameters] = form.Parameters;

			this.IsCompleted = true;
		}
	}
}
